package st.business.tepth.business.user.busnumber.workholder.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import st.business.tepth.R;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.DiagnoseBean;
import st.business.tepth.business.bean.PartBean;
import st.business.tepth.business.bean.ProgramBean;
import st.business.tepth.business.bean.RepairTaskBean;
import st.business.tepth.business.bean.RepairTaskTypeBean;
import st.business.tepth.business.event.DiagnoseSelectEvent;
import st.business.tepth.business.user.busnumber.workholder.adapter.TroubleProgramAdapter;
import st.business.tepth.config.ItemFields;
import st.business.tepth.config.Url;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.net.callback.IError;
import st.shadow.library.core.net.callback.ISuccess;
import st.shadow.library.core.net.data.ObjConverter;
import st.shadow.library.core.net.rx.RxRestClient;
import st.shadow.library.ui.indicator.magicindicator.MagicIndicator;
import st.shadow.library.ui.indicator.magicindicator.ViewPagerHelper;
import st.shadow.library.ui.indicator.magicindicator.buildins.UIUtil;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.CommonNavigator;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.indicators.WrapPagerFillIndicator;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.titles.badge.BadgeAnchor;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.titles.badge.BadgePagerTitleView;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.titles.badge.BadgeRule;
import st.shadow.library.ui.recycler.MultipleItemEntity;

/**
 * @author zhangyu
 * @date 2019/2/20
 * 关联其它作业方案
 */
public class DialogContactOtherProgram extends Dialog {

    private ViewPager viewPager;
    private List<ProgramBean> mSelectList = new ArrayList<>();
    private TextView mTvConfirm;
    private Disposable mDisposable;

    public DialogContactOtherProgram(final Context context,
                                     final OnItemChooseListener<List<MultipleItemEntity>> listener,
                                     int repairId, final DiagnoseBean diagnoseBean) {
        super(context);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_contact_other_program, null);
        final ConstraintLayout container = view.findViewById(R.id.layout_container);
        viewPager = view.findViewById(R.id.view_pager_trouble);
        mTvConfirm = view.findViewById(R.id.tv_confirm);
        mTvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    if (mSelectList != null && !mSelectList.isEmpty()) {
                        List<MultipleItemEntity> entityList = new ArrayList<>();
                        for (ProgramBean programBean : mSelectList) {
                            //诊断id改为自己的
                            programBean.setFault_diagnostic_id(diagnoseBean.getId());
                            programBean.setDiagnostic_name(diagnoseBean.getName());
                            programBean.setPhenomenon_id(diagnoseBean.getRepair_phenomenon_id());
                            //关联的
                            programBean.setRelation_state(1);
                            //关联项物料数量为0
                            PartBean partBean = programBean.getPart();
                            if (partBean != null) {
                                partBean.setVal(0);
                            }
                            PartBean material = programBean.getMaterial();
                            if (material != null) {
                                material.setVal(0);
                            }
                            entityList.add(MultipleItemEntity.builder()
                                    .setItemType(TroubleProgramAdapter.TYPE_RELEVANCE_UN_CONFIRM)
                                    .setField(ItemFields.ITEM_OBJ, programBean)
                                    .build());
                        }
                        listener.onChoose(entityList);
                    }
                }
                dismiss();
            }
        });
        view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        final MagicIndicator indicator = view.findViewById(R.id.indicator);

        EventBus.getDefault().register(this);
        setContentView(view);
        addTopView(R.layout.view_loading, container);
        mDisposable = RxRestClient.builder().url(Url.GetAllRelevanceProgram)
                .params("token", UserManager.getInstance().getToken())
                .params("repairId", repairId)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        RepairTaskTypeBean repairTaskTypeBean =
                                new ObjConverter<RepairTaskTypeBean>().convert(response
                                        , new TypeReference<RepairTaskTypeBean>() {
                                        });
                        if (repairTaskTypeBean != null) {
                            ArrayList<RepairTaskBean> repairTaskList =
                                    repairTaskTypeBean.getRepairTaskList();
                            if (repairTaskList != null) {
                                final List<ViewContactProgram> list = new ArrayList<>();
                                for (RepairTaskBean taskBean : repairTaskList) {
                                    list.add(new ViewContactProgram(getContext(), taskBean));
                                }
                                viewPager.setAdapter(new PagerAdapter() {

                                    @Override
                                    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                                        container.removeView((View) object);
                                    }

                                    @NonNull
                                    @Override
                                    public Object instantiateItem(@NonNull ViewGroup container, int position) {
                                        container.addView(list.get(position), ViewGroup.LayoutParams.MATCH_PARENT,
                                                ViewGroup.LayoutParams.MATCH_PARENT);
                                        return list.get(position);
                                    }

                                    @Override
                                    public int getCount() {
                                        return list.size();
                                    }

                                    @Override
                                    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
                                        return view == o;
                                    }
                                });
                                CommonNavigator commonNavigator = new CommonNavigator(getContext());
                                commonNavigator.setLeftPadding(0);
                                commonNavigator.setRightPadding(0);
                                commonNavigator.setAdapter(new ClassificationAdapter(repairTaskList));

                                indicator.setNavigator(commonNavigator);
                                ViewPagerHelper.bind(indicator, viewPager);
                            }
                        }
                        removeTopView(container);
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        removeTopView(container);
                    }
                })
                .build().post();
    }


    @Override
    public void dismiss() {
        EventBus.getDefault().unregister(this);
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        super.dismiss();
    }

    @Subscribe
    public void onDiagnoseSelectEvent(DiagnoseSelectEvent event) {
        if (event.isSelect) {
            mSelectList.add(event.diagnoseBean);
        } else {
            mSelectList.remove(event.diagnoseBean);
        }
        setEnable(mTvConfirm, !mSelectList.isEmpty());
    }

    private void setEnable(TextView tvConfirm, boolean isEnable) {
        tvConfirm.setBackgroundResource(isEnable ?
                R.drawable.shape_btn_operation_n :
                R.drawable.shape_btn_operation_t);
        tvConfirm.setTextColor(isEnable ? Color.parseColor("#333333") :
                Color.parseColor("#ffffff"));
        tvConfirm.setEnabled(isEnable);
    }

    private void getContactData() {

    }


    private class ClassificationAdapter extends CommonNavigatorAdapter {
        private ArrayList<RepairTaskBean> mList;

        public ClassificationAdapter(ArrayList<RepairTaskBean> list) {
            mList = list;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public IPagerTitleView getTitleView(Context context, final int index) {
            RepairTaskBean repairTaskBean = mList.get(index);
            final BadgePagerTitleView badgePagerTitleView = new BadgePagerTitleView(context);
            SimplePagerTitleView simplePagerTitleView =
                    new ColorTransitionPagerTitleView(context);
            simplePagerTitleView.setText(mList.get(index).getVehicle_series_name());
            simplePagerTitleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
            simplePagerTitleView.setGravity(Gravity.CENTER);
            simplePagerTitleView.setBackground(context.getResources()
                    .getDrawable(R.drawable.shape_solid_trans_with_yellow_stroke));
            simplePagerTitleView.setNormalColor(Color.parseColor("#333333"));
            simplePagerTitleView.setSelectedColor(Color.parseColor("#333333"));
            simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    viewPager.setCurrentItem(index);
                    badgePagerTitleView.setBadgeView(null); // cancel badge when click tab
                }
            });
            badgePagerTitleView.setInnerPagerTitleView(simplePagerTitleView);

            // setup badge

            TextView badgeTextView = (TextView) LayoutInflater.from(context).inflate(R.layout.view_badge, null);
            badgeTextView.setText(repairTaskBean.getFaultPhenomenonList() == null ?
                    "0" : (repairTaskBean.getFaultPhenomenonList().size() + ""));
            badgePagerTitleView.setBadgeView(badgeTextView);
            // set badge position
            badgePagerTitleView.setXBadgeRule(new BadgeRule(BadgeAnchor.CONTENT_RIGHT, +UIUtil.dip2px(context, 6)));
            badgePagerTitleView.setYBadgeRule(new BadgeRule(BadgeAnchor.CONTENT_TOP, -UIUtil.dip2px(context, 6)));

            // don't cancel badge when tab selected
            badgePagerTitleView.setAutoCancelBadge(false);
            return badgePagerTitleView;
        }

        @Override
        public IPagerIndicator getIndicator(Context context) {
            WrapPagerFillIndicator indicator = new WrapPagerFillIndicator(context);
            indicator.setRoundRadius(0);
            indicator.setHorizontalPadding(UIUtil.dip2px(context, 20));
            indicator.setFillColor(Color.parseColor("#f1b647"));
            return indicator;
        }
    }

    private void addTopView(int resourceId, ViewGroup group) {
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        );
        group.addView(LayoutInflater.from(getContext()).inflate(resourceId, null)
                , group.getChildCount(), layoutParams);
    }

    private void removeTopView(ViewGroup group) {
        group.removeViewAt(group.getChildCount() - 1);
    }
}
